import Config from '../config.js'
import Config2 from './config2.js'
import Util from './util2.js' 
export default function(obj) {
   
    let parameter = {
      url: "",
      type: "GET",
      dataType: "json",
      headers: {
        "Content-type": 'application/x-www-form-urlencoded' , //"application/x-www-form-urlencoded"
      },
      data: {}
    }
    parameter = Object.assign(parameter, obj);
  
    //将config文件中的常量整合进来
    parameter.headers = Object.assign(parameter.headers, Config.headers);
    if (parameter.url.indexOf('app/weixin/login') == -1) {
      parameter.headers.token = wx.getStorageSync('cusmallToken') || '';
    }
    parameter.data.cusmallToken = wx.getStorageSync('cusmallToken');
  //判断头类型是否json,如果是则需要转一下参数类型
    if(parameter.headers['Content-type'] === 'application/json'){
      parameter.data = JSON.stringify(parameter.data);
    }
    return new Promise(function(resolve, reject) {
      // debugger
      wx.request({
        header: parameter.headers,
        method: parameter.type,
        url: Config.config.pageDomain+parameter.url,
        dataType: parameter.dataType,
        data: parameter.data,
        fail: function() {
            wx.showToast({
                title: "服务器升级中，请稍后再试",
                icon: 'none',
                duration: 2000
              })
        },
        success: function ({ data, statusCode}) {

            if(data.ret==-4003||data.ret==-4000) {
               //过期清除所有缓存
               let referrerId = wx.getStorageSync(Config2.referrerIdKey);
               Util.clearStorage(Config2.retainKey);
               wx.setStorageSync(Config2.referrerIdKey, referrerId);
               const app = getApp()
               let pages = getCurrentPages();
               if (app.globalData.isReturnLogin !== true) {
                 app.globalData.isReturnLogin = true;
                 wx.navigateTo({
                   url: '/subPackages/pages/login/login?from=' + pages[pages.length - 1].route,
                 })
                 setTimeout(() => {
                   app.globalData.isReturnLogin = false;
                 }, 2000)
               } else {
                 //解决页面触发太多需要校验token的请求，重复跳转到登录页问题
                 setTimeout(() => {
                   app &&(app.globalData.isReturnLogin = false);
                 }, 2000 )
               }
              }else{
                resolve(data);
              }
             
        }
      });
    })
  }